package com.base.cn.platform.os.controller.manage.main;

import com.base.cn.platform.os.common.AdminBaseController;
import com.base.cn.platform.os.common.constants.CommonConstants;
import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.rsa.WebRsaUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.web.WebUtils;
import com.base.cn.platform.os.service.manage.sysUser.SysUserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录Controller
 *
 * @author s.li
 * @create 2018-03-06 16:37
 */
@Controller
public class LoginController extends AdminBaseController {

    @Autowired
    private SysUserLoginService sysUserLoginService;
    @Autowired
    private CustomCacheChannel customCacheChannel;

    @RequestMapping("/notLoginJump")
    public String notLoginJump(){
        return resultPage("/manage/main/not-login-jump");
    }

    /**
     * 跳转登录页面
     * @return
     */
    @RequestMapping("/login")
    public String login(Model model) throws Exception{
        Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
        model.addAttribute("keyMap",keyMap);
        return resultPage("manage/main/login");
    }

    /**
     * 跳转申请体验账号页面
     * @return
     */
    @RequestMapping("/register")
    public String register(){
        return resultPage("manage/main/register");
    }

    /**
     * 执行登录入口
     * @param userName 用户名
     * @param password 密码
     * @param gapLeft 验证证图坐标
     * @param moveLeft 验证图移动坐标
     * @return Map<String,Object>
     */
    @RequestMapping("/doLogin")
    @ResponseBody
    public Map<String,Object> doLogin(HttpServletRequest request,
                                      HttpServletResponse response,
                                      @RequestParam("sign") String sign,
                                      @RequestParam(value = "userName",required = false) String userName,
                                      @RequestParam(value = "password",required = false) String password,
                                      @RequestParam(value = "gapLeft",required = false,defaultValue = "0")  String gapLeft,
                                      @RequestParam(value = "moveLeft",required = false,defaultValue = "0") String moveLeft) throws Exception{
        Map<String,Object> params = new HashMap<>();
        params.put("username",userName);
        password = WebRsaUtils.decrypt(customCacheChannel,sign,password,false);
        gapLeft = WebRsaUtils.decrypt(customCacheChannel,sign,gapLeft,false);
        moveLeft = WebRsaUtils.decrypt(customCacheChannel,sign,moveLeft,true);
        params.put("password",password);
        Map<String,Object> resultMap = sysUserLoginService.executeLogin(params,Integer.parseInt(gapLeft),Integer.parseInt(moveLeft));
        if(!ResultUtil.getSuccess(resultMap)){//登录失败
            String status = (String)resultMap.get("status");
            if(StringUtils.isNotEmpty(status) && status.equals("1")){
                return ResultUtil.to(resultMap,"该账号已在另一个的环境已经登录","/admin/manage/index");
            }
            Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
            resultMap.put("keyMap",keyMap);
        }else{//登录成功
            String sessionId = (String)resultMap.get("sessionId");
            WebUtils.setCookie(response, CommonConstants.ADMIN_LOGIN_COOKIE,sessionId,1);
        }
        return ResultUtil.to(resultMap,"/admin/manage/index");
    }

    /**
     * 执行申请体验账号
     * @param account 账号（手机号）
     * @param captcha 手机验证码
     * @param password 密码
     * @param confirmPwd 确认密码
     * @return Map<String,Object>
     */
    @RequestMapping("/doRegister")
    @ResponseBody
    public Map<String,Object> doRegister(@RequestParam(value = "account",required = false) String account,
                                         @RequestParam(value = "captcha",required = false) String captcha,
                                          @RequestParam(value = "password",required = false) String password,
                                         @RequestParam(value = "confirmPwd",required = false) String confirmPwd){
        account = account.trim();
        Map<String,Object> paramsSysUser = new HashMap<>();
        paramsSysUser.put("account",account);
        paramsSysUser.put("password",password);
        paramsSysUser.put("confirmPwd",confirmPwd);
        paramsSysUser.put("captcha",captcha);
        paramsSysUser.put("regType",2);//用户注册创建来源，2表示页面体验账号申请
        return sysUserLoginService.executeRegister(paramsSysUser);
    }

    /**
     * 退出登录
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request,HttpServletResponse response){
        String sessionId = WebUtils.getCookie(request,CommonConstants.ADMIN_LOGIN_COOKIE);
        BigDecimal userId = loginUtil.getLoginUserId(request);
        boolean outOk = sysUserLoginService.executeLogout(sessionId,userId);
        if(outOk){
            WebUtils.deleteCookie(request,response,CommonConstants.ADMIN_LOGIN_COOKIE);
        }
        return "redirect:/login";
    }

    /**
     * 修改当前登录用户的密码
     * @param request HttpServletRequest
     * @param oldPassword 原密码
     * @param newPassword 新密码
     * @param confirmPassword 确认密码
     * @return Map<String,Object>
     */
    @RequestMapping("/admin/updateThisPwd")
    @ResponseBody
    public Map<String,Object> updateThisPwd(HttpServletRequest request,
                                            @RequestParam("oldPassword") String oldPassword,
                                            @RequestParam("newPassword") String newPassword,
                                            @RequestParam("confirmPassword") String confirmPassword){
        BigDecimal userId = loginUtil.getLoginUserId(request);
        return sysUserLoginService.updateThisPwd(userId,oldPassword,newPassword,confirmPassword);
    }

    @RequestMapping("/noAuthority")
    public String noAuthority(){
        return resultPage("/manage/main/noAuthority");
    }

    /**
     *发送验证码
     * @param account
     * @return
     */
    @RequestMapping("/sendCaptcha")
    @ResponseBody
    public Map<String,Object> sendCaptcha(@RequestParam("account") String account) {
        if(!StringUtils.isNotEmpty(account)){
            return  ResultUtil.ERROR("手机号不能为空");
        }if(!StringUtils.isMobile(account)){
            return ResultUtil.ERROR("手机号格式不正确");
        }
        return sysUserLoginService.sendCaptcha(account);

    }

}
